﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;

namespace Spacer {
	public class SoundScript {
		public class SoundScriptCfg {
			public string Name { get; set; }
			public Range<float> Volume { get; set; }
			public Range<float> Pitch { get; set; }
			public string SoundName { get; set; }
			public string[] RndSoundNames { get; set; }

			// ----------

			public SoundScriptCfg() {
				Name = "";
				Volume = new Range<float>( 1.0f );
				Pitch = new Range<float>( 1.0f );
				SoundName = "";
				RndSoundNames = new string[]{};
			}
		}

		// ----------

		string m_strName;
		Range<float> m_rVolume;
		Range<float> m_rPitch;
		SoundEffect m_Sound;
		SoundEffect[] m_RndSounds;

		// ----------

		public string Name {
			get { return m_strName; }
			set { m_strName = value; }
		}

		public Range<float> Volume {
			get { return m_rVolume; }
			set { m_rVolume = value; }
		}

		public Range<float> Pitch {
			get { return m_rPitch; }
			set { m_rPitch = value; }
		}

		public SoundEffect Sound {
			get { return m_Sound; }
			set { m_Sound = value; }
		}

		public SoundEffect[] RndSounds {
			get { return m_RndSounds; }
			set { m_RndSounds = value; }
		}

		// ----------

		public SoundScript( string strName ) {
			m_strName = strName;

			SoundScriptCfg cfg = XmlObjectCfg<SoundScriptCfg>.Load( Configuration.ContentPath + "/Scripts/" + strName + ".xml", null );
			m_rVolume = cfg.Volume;
			m_rPitch = cfg.Pitch;
			m_Sound = (cfg.SoundName != null && cfg.SoundName.Length > 0 ? Main.SoundEffects[cfg.SoundName] : null);
			m_RndSounds = new SoundEffect[cfg.RndSoundNames.Length];
			
			for(int i=0;i<m_RndSounds.Length;i++) {
				m_RndSounds[i] = Main.SoundEffects[cfg.RndSoundNames[i]];
			}
		}

		// ----------

		public void Play() {
			float rv = Globals.Random * (m_rVolume.Max-m_rVolume.Min) + m_rVolume.Min;
			float rp = Globals.Random * (m_rPitch.Max-m_rPitch.Min) + m_rPitch.Min;

			if( m_RndSounds != null && m_RndSounds.Length > 0 ) {
				int index = (int)((float)m_RndSounds.Length * Globals.Random);
				m_RndSounds[index % m_RndSounds.Length].Play( rv, rp, 0f );
			} else if( m_Sound != null ) {
				m_Sound.Play( rv, rp, 0f );
			}
		}
	}
}
